package com.ztools.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.Gravity;

import com.ztools.common.R;


public class CircleTextView extends AppCompatTextView {
    private int backgoundColor;

    public CircleTextView(Context context) {
        super(context);
        init(context, null);
    }

    public CircleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CircleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (text.toString().contains("申购")) {
            backgoundColor = Color.parseColor("#FFFE8D60");
        } else if (text.toString().contains("定投")) {
            backgoundColor = Color.parseColor("#FF58BCFB");
        } else if (text.toString().contains("赎回")) {
            backgoundColor = Color.parseColor("#FFB880F6");
        } else if (text.toString().contains("转换")) {
            backgoundColor = Color.parseColor("#FFF68080");
        }
        super.setText(text, type);
    }

    private void init(Context context, AttributeSet attrs) {
        setIncludeFontPadding(false);//关闭文字边距
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.common_CircleTextView);
        backgoundColor = ta.getColor(R.styleable.common_CircleTextView_common_circle_backgroundColor, ContextCompat.getColor(getContext(), R.color.common_white));
        this.setGravity(Gravity.CENTER);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        float width = this.getMeasuredWidth();
        float height = this.getMeasuredHeight();
        Paint paint = this.getPaint();
        paint.setColor(backgoundColor);
        float xRadius = width - getPaddingLeft() - getPaddingRight();
        float yRadius = height - getPaddingTop() - getPaddingBottom();
        float radius;
        if (xRadius > yRadius) {
            radius = yRadius / 2;
        } else {
            radius = xRadius / 2;
        }
        float startX = getPaddingLeft() + radius;
        float startY = getPaddingTop() + radius;
        canvas.drawCircle(startX, startY, radius, paint);
        paint.setColor(Color.parseColor("#FFFFFF"));
        super.onDraw(canvas);
    }

    /**
     * 设置背景颜色
     *
     * @param color
     */
    public void setCircleBackgroundColor(@ColorRes int color) {
        this.backgoundColor = color;
        postInvalidate();
    }


}
